package cn.com.czpb.client.module.newsnew;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.litepal.LitePal;
import org.litepal.crud.DataSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

import butterknife.OnClick;
import cn.com.czpb.client.R;
import cn.com.czpb.client.api.InterfaceJsonfile;
import cn.com.czpb.client.app.BaseFragment;
import cn.com.czpb.client.app.MyActivitymanager;
import cn.com.czpb.client.custorm.smartrefreshalayout.ClassHeader_other;
import cn.com.czpb.client.custorm.swiperefreshhelper.SwipeRefreshHelper_index;
import cn.com.czpb.client.model.base.BaseEntity;
import cn.com.czpb.client.model.diantai.RadioBean;
import cn.com.czpb.client.model.diantai.RadioEntity;
import cn.com.czpb.client.model.diantai.RadioTypeBean;
import cn.com.czpb.client.model.event.PraiseEvent;
import cn.com.czpb.client.model.event.PublishEventForPublisher;
import cn.com.czpb.client.model.news.NewsBean;
import cn.com.czpb.client.model.news.NewsChannelBean;
import cn.com.czpb.client.model.news.NewsListEntity;
import cn.com.czpb.client.model.newsnew.NewsNewListBean;
import cn.com.czpb.client.model.newsnew.NewsNewListEntity;
import cn.com.czpb.client.module.diantai.adapter.RadioListAdapter;
import cn.com.czpb.client.module.news.NewsBaseFragment;
import cn.com.czpb.client.module.news.adapter.NewsItemListViewAdapterNew;

import cn.com.czpb.client.module.newsnew.adapter.NewsAdapter;
import cn.com.czpb.client.module.video.utils.VideoPlayerHelper;
import cn.com.czpb.client.net.Factory;
import cn.com.czpb.client.utils.DeviceUtils;
import cn.com.czpb.client.utils.LogUtils;
import cn.com.czpb.client.utils.PageCtrl;
import cn.com.czpb.client.utils.ParamUtils;
import cn.com.czpb.client.utils.StatUtils;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2018/6/21.
 */

public class NewsFragment extends BaseFragment implements BaseQuickAdapter.OnItemChildClickListener, OnRefreshListener, OnLoadmoreListener {
    @BindView(R.id.refresh_id)
    SmartRefreshLayout refresh_id;
    @BindView(R.id.recycler_id)
    RecyclerView recycler_id;

    @BindView(R.id.rl_live)
    LinearLayout rl_live;
    @BindView(R.id.ll_zhongyang)
    LinearLayout ll_zhongyang;
    @BindView(R.id.ll_bendi)
    LinearLayout ll_bendi;
    @BindView(R.id.ll_jingxuan)
    LinearLayout ll_jingxuan;
    @BindView(R.id.ll_collection)
    LinearLayout ll_collection;

    @BindView(R.id.tv_zhongyang)
    TextView tv_zhongyang;
    @BindView(R.id.tv_bendi)
    TextView tv_bendi;
    @BindView(R.id.tv_jingxuan)
    TextView tv_jingxuan;
    @BindView(R.id.tv_collection)
    TextView tv_collection;


    NewsAdapter mAdapter;


    int Page = 1;
    int PageSize = 15;
    boolean isRefresh = false;
    String typeId;
    String myflag;
    List<NewsChannelBean> typeBeanList;

    public static NewsFragment newInstance() {
        NewsFragment fragment = new NewsFragment();
        return fragment;
    }


    @Override
    public int setMyContentView() {
        return R.layout.fragment_live_new;
    }

    @Override
    public void initView() {

    }

    @Override
    public void initData() {


        ll_zhongyang.setSelected(true);

        typeBeanList = LitePal.findAll(NewsChannelBean.class);

        if (typeBeanList.size() > 0) {
            tv_zhongyang.setText(typeBeanList.get(0).getCnname());
            tv_bendi.setText(typeBeanList.get(1).getCnname());
            tv_jingxuan.setText(typeBeanList.get(2).getCnname());
        } else {
            tv_zhongyang.setText("本地新闻萃播");
            tv_bendi.setText("中央新闻联播");
            tv_jingxuan.setText("精选推荐");
        }

        tv_collection.setText("我的收藏");
        typeId = typeBeanList.get(0).getTid();
        LayoutInflater inflater = LayoutInflater.from(activity);
        int size = typeBeanList.size();
//

        initAdapter();
    }

    @OnClick({R.id.ll_zhongyang, R.id.ll_bendi, R.id.ll_jingxuan, R.id.ll_collection})
    public void OnClick(View view) {
        ll_zhongyang.setSelected(false);
        ll_bendi.setSelected(false);
        ll_jingxuan.setSelected(false);
        ll_collection.setSelected(false);


        switch (view.getId()) {
            case R.id.ll_zhongyang:
                typeId = typeBeanList.get(0).getTid();
                ll_zhongyang.setSelected(true);
                myflag="0";
                break;
            case R.id.ll_bendi:
                ll_bendi.setSelected(true);
                typeId = typeBeanList.get(1).getTid();
                myflag="0";
                break;
            case R.id.ll_jingxuan:
                ll_jingxuan.setSelected(true);
                typeId = typeBeanList.get(2).getTid();
                myflag="0";
                break;
            case R.id.ll_collection:
                ll_collection.setSelected(true);
                myflag="1";
                break;
        }
        initList(typeId, true);
    }

    private void initAdapter() {
        mAdapter = new NewsAdapter(null,0);
        refresh_id.setRefreshHeader(new ClassHeader_other(activity));
        GridLayoutManager manager = new GridLayoutManager(activity, 3);
        recycler_id.setLayoutManager(manager);
        recycler_id.setAdapter(mAdapter);
        refresh_id.setOnRefreshListener(this);
        refresh_id.setOnLoadmoreListener(this);
        mAdapter.setOnItemChildClickListener(this);
        initList(typeId, false);
    }

    private void initList(String typeid, final boolean cleared) {
        Map<String, String> map = new HashMap<>();
        map.put("siteid", InterfaceJsonfile.SITEID);
        map.put("tid", typeid);
        map.put("Page", Page + "");
        map.put("PageSize", PageSize + "");
        map.put("device", DeviceUtils.getMyUUID(activity));
        map.put("myflag", myflag);

        LogUtils.i("device-->" + DeviceUtils.getMyUUID(activity));
        LogUtils.i("device-->" + DeviceUtils.getMyUUID(activity));
        Factory.provideHttpService()
                .getnewslist(ParamUtils.getRequestParam(map))
                .subscribeOn(Schedulers.io())
                .filter(new Func1<NewsListEntity, Boolean>() {
                    @Override
                    public Boolean call(NewsListEntity entity) {

                        if ("200".equals(entity.code)) {
                            LogUtils.i("200--list>成功");
                            return true;
                        }
                        LogUtils.i("200--list>失败");
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewsListEntity>() {
                    @Override
                    public void call(NewsListEntity entity) {
                        disMissDialog_index();
                        disMissDialog();
                        if (isRefresh) {
                            refresh_id.finishRefresh();
                        }

                        if ("200".equals(entity.code)) {
                            setListData(entity.data, cleared);
                            if (isRefresh) {
                                LogUtils.i("200-->saveAll");
                                DataSupport.deleteAll(NewsNewListBean.class);
//                                DataSupport.saveAll(entity.data);
                            }

                        } else {
//                            TUtils.toast(entity.msg);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
//                        if (isRefresh) {
//                            refresh_id.finishRefresh();
//                            List<NewsBean> list = DataSupport.findAll(NewsBean.class);
//                            setListData(list,false);
//                        }
                        LogUtils.i("异常-->" + throwable.toString());
                        mAdapter.loadMoreFail();
                    }
                });
    }

    private void setListData(List<NewsBean> list, boolean cleared) {
        if (cleared) {
            mAdapter.setNewData(list);
        } else {
            if (isRefresh) {
                mAdapter.setNewData(list);
                mAdapter.notifyDataSetChanged();
            } else {
                mAdapter.addData(list);
                mAdapter.notifyDataSetChanged();
            }
        }

    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        Page++;
        initList(typeId, false);
        refresh_id.setLoadmoreFinished(true);
        refresh_id.finishLoadmore();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.getLayout().postDelayed(new Runnable() {
            @Override
            public void run() {
                isRefresh = true;
                Page = 1;
                initList(typeId, false);
            }
        }, 2000);
        refresh_id.setLoadmoreFinished(false);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        final NewsBean newsBean = (NewsBean) adapter.getItem(position);

        ////REFACTOR: 2017/8/18 添加浏览量bug

        StatUtils.addCount(newsBean);
        MyActivitymanager.pushActivity(activity, newsBean, newsBean.getTid(), "newsitem", newsBean.getRvalue());
        LogUtils.e("rtype--" + newsBean.getRtype());

    }
}